package com.huatai.bpmn.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huatai.bpmn.entity.UserGroupEntity;
import com.huatai.bpmn.mapper.UserGroupMapper;
import com.huatai.bpmn.service.UserGroupService;
import com.huatai.bpmn.service.UserService;
import com.huatai.user.dubbo.UserDubboApi;
import com.huatai.user.entity.User;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


/**
 * 用户分组，用于审批
 *
 * @author yxy
 * @email yuanxy999@126.com
 * @date 2024-08-22 10:57:56
 */
@Service("sysUserGroupService")
public class GroupServiceImpl extends ServiceImpl<UserGroupMapper, UserGroupEntity> implements UserGroupService {

	@Autowired
	private UserService userService;
	@DubboReference(timeout = 30000, check = false, retries = 0)
	private UserDubboApi userDubboApi;

	/**
	 * 用户分组列表
	 * @return
	 */
	@Override
	public List<UserGroupEntity> listByUser() {
		List<UserGroupEntity> list = this.list();
		list.forEach(x -> {
			String[] userArr = x.getUsers().split(",");
			String userName="";
			for (String s : userArr) {
				User user = userDubboApi.getUser(Long.valueOf(s));
				userName+=user.getRealName()+",";
			}
			if (userName.endsWith(",")){
				userName=userName.substring(0,userName.lastIndexOf(","));
			}
			x.setUserName(userName);
		});
		return list;
	}

	/**
	 * 用户分组新增修改
	 * @param sysUserGroupEntity
	 * @return
	 */
	@Override
	public boolean addOrUpdate(UserGroupEntity sysUserGroupEntity) {
		String users = sysUserGroupEntity.getUsers();
		if (users.endsWith(",")){
			users=users.substring(0,users.lastIndexOf(","));
		}
		sysUserGroupEntity.setUsers(users);
		return this.saveOrUpdate(sysUserGroupEntity);
	}

	@Override
	public List<String> getUserByMyKey(String myKey) {
		UserGroupEntity userGroupEntity = this.getOne(Wrappers.<UserGroupEntity>lambdaQuery().eq(UserGroupEntity::getMyKey, myKey));
		String users = userGroupEntity.getUsers();
		List<String> list = Arrays.stream(users.split(",")).collect(Collectors.toList());
		return list;
	}
}
